package com.chijun.mform.create.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuProvider;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chijun.mform.FormBuilder;
import com.chijun.mform.create.IServerSaveOverResult;
import com.chijun.mform.create.IWaitResult;
import com.chijun.mform.create.dialog.SelectSaveModeDialog;
import com.chijun.mform.create.field.Field;
import com.chijun.mform.create.mode.FormAdmin;
import com.chijun.mform.create.mode.FormApprovePerson;
import com.chijun.mform.create.mode.FormApproveProcess;
import com.chijun.mform.create.mode.FormConfig;
import com.chijun.mform.R;
import com.chijun.mform.create.fragment.FormAddFieldFragment;
import com.chijun.mform.create.fragment.FormAddProcessFragment;
import com.chijun.mform.create.fragment.WriteBaseInformationFragment;
import com.chijun.mform.create.mode.Form;
import com.chijun.mform.create.mode.FormField;
import com.chijun.mform.create.mode.FormFieldOption;
import com.chijun.mform.create.mode.FormFilled;
import com.chijun.mform.create.mode.FormGroup;
import com.chijun.mform.create.mode.FormIcon;
import com.chijun.mform.create.mode.FormOptionReField;
import com.chijun.mform.create.mode.FormProcessToFieldPermission;
import com.chijun.mform.create.mode.FormSaveData;
import com.chijun.mform.create.mode.FormUser;
import com.chijun.mform.test.CreateFormServiceImpl;
import com.example.ccj.b.a.BaseActivity;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.b.c.dialog.SureOrCancelDialog;
import com.example.ccj.u.FragmentUtils;
import com.example.ccj.u.GenerateId;
import com.example.ccj.u.JsonUtils;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.ThreadUtils;
import com.example.ccj.u.ThreadUtilsListener;
import com.example.ccj.u.ToastUtils;
import com.example.ccj.u.server.MyObserver;
import com.example.ccj.u.server.Result;
import com.example.ccj.u.sqlite.SqliteExcuteCommand;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
/*
 *
 *
 *    /\_/\
 *   (  o o  )
 *    > ^ <
 *  /  ----  \
 * |          |
 *  \  ----  /
 *
 *
 *
 */

/*
.,:::,
;.,.....................................:ish398GXX&XX83s,
BBBHA&8S1i.........................:s59XABMBBBBBBHHHHHHHBMBS
HHHHHHBBBBHX5;..................s9&BMBBHHHHHHHHAA&&&AHHHHAB#5
1shS9GAHHHHBMB8;.............;3HMBHHHHHHHAX951ri;;;;isXHHHHBH;
, ,.,:i5&HHHHHMH89GGXXXXXGG98BBBAHHHHH&91i:,..,,,,,,,,5HHHHHM5
:.,,:,,.;GHHHHHBBBBHHHHHHBBBBHHHHHHHX1:..,,,,:::,,:,:,sAHHHHM8
:.,,:,.:sGHHHHHHHHHHHHHHHHHHAHHHHHHH&G3hi:,,,,::,,,,,,rAHHHHM&
:.:,,:1GHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHAGSr:,,:::::,,r&HHHHBB
:.,:1GHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHGh;,,:::,,rAHHHHBB
,.sGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH&5;,,,:,1HHHHHBM
r3HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHX1,,::5HHHHHBM
HHHHX3559HHHHHHHHHHHHHHHHHHHAXG8898HBHHHHHHHHHHHHH9;,:9HHHHHBB
HA9s:,..,hAHHHHHHHHHHHHHHH&S39s:..sM83&HHHHHHHHHHHHGii&HHHHHBA
9r,.,:::,,9HHHHHHHHHHHHHH3;5&H&G88HG;:8MBHHHHHHHHHHHX8HHHHHHMG
,.,:::::,:9HHHHHHHHHHHHH3:,i5XA911r,,S#9XHHHHHHHHHHHHHHHHHHH#5
,.,,,,,:::1SS39888GGX&AG;,,, .8#s...,rX&XHHHHHHHHHHHHHHHHHHBH;
,.,,,,,:::,.,.,,,,:::;;:,:,:18A8;,r1s;:1GBBHHHHHHHHHHHHHHHHM3
,.,,,,,,,,::::,,,,,,,,,,,,,:S3r,iXA8G&X5;5HHHHHHHHHHHHHHHHMA,
,.,,,,,,,,,,,,,,,:::,,:::,::..,:GMs,,;h8sr&HHHHHHHHHHHHHHBM1
,.,,,:,,,,,,,,,,,,:,,,,,,,,,,,,:h1,,,,,,,;GHHHHHHHHHHHHHHMA,
,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,:,,,::::::,,9HHHHHHHHHHHHHABH,
,.,:,,:,:::,,,,,,,,,,,,,,,,,,,::::::::::,,SHHHHHHHHHHHHHHBM3;
Sr:,,,:::::::::,,,,,,,,,,,,,,,::::,,,,,,,,5HHHHHHHHHHHHHHHMAXG
MMA3r,,,:,,,:::,,,,,,,,,,,,,,,,,,,,:;rsi,,hHHHHHHHHHHHHHHHM3.1
8&##MX1,,,,,:::,,,,,:::,,,,..,;s59XHB##X:,1AHHHHHHHHHHHHHHM&.
BBM####&1:,,,,...,,,,::,,,ih9&B##MAG3hs;,,1AHHHHHHHHHHHHHHBMS
ir55S8&B8:,;s5399Ss;,,,;3A#######MBHHAA&9:sAHHHHHHHHHHHHHHHB8.
;,ir;,,:,,SHBMGhhXBAS:,;9&G889S5S3SS398X3,1AHHHHHHHHHHHHHHAMhi
;,:;:,,,,,GMAA9hh9AMX:,,,,,,;ri:;r;,.....i8HHHHHHHHHHHHHHHBMr9
,.,,,::::,:sS9GXXG9h;,::,,,,:;ri:;rsi;is3&HHHHHHHHHHHHHBMM#S 8
: .,,,:,,,,,i11r:...,:,:::,,:,,,,,:SA&AHHHHHHHHHHHHBBBBBMMS ,
&85s;,..,,,3&88XX9s:,,,:,,:,:,,:::,5HHHHHHHHHHHHBBBBBHHAHMS .i
iS&A&X95si:;:..,rSh,,,,,,,,,,,,,,,.i&HHHHBBHH&BMHHHHAHHHHBMGXA
. rhS3GM#HAX835hriiii;;;;;;;;irrsh53HMBBBMMHX8&MMHHHHHHHHHMASh
. ;1hhGMBHHBBBM#A&&&&&&&&X&&&&&&XXG93S55S339999XMBHHHHHHHMX1h
. .rh5GMBHAAHBM3hh555555555555hhhhhh55hhhhhhh1hHMAHHHHHHM8hh
. ,rh9HMMBMB8hh55555hh1ssriii;;;;;;:;irh55hh5HMHHHHHHMH5hh
. ,;sS989Shhh1sri:,.. .i1555HMHAAAHMHShh5
. .,::,.. :i18BMBBMBG5h551
. .i5993h111s:

/**
 * 创建表单主入口
 * 传入数据
 * 1、表单类型 "form_type" int类型 0：数据表单  1：流程表单
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/11/16 18:03
 */
public class CreateFormActivity extends BaseActivity {
    public static final int FORM_TYPE_DATA = 0;       //数据表单标志
    public static final int FORM_TYPE_PROCESS = 1;     //流程表单标志
    public static final int FORM_SAVE_LOCATION = 1;     //保存本地标志
    public static final int FORM_SAVE_SERVER = 2;       //保存服务器标志

    
    WriteBaseInformationFragment writeBaseInformationFragment;
    FormAddFieldFragment formAddFieldFragment;
    FormAddProcessFragment formAddProcessFragment;

    RadioGroup radioGroup;
    FormConfig formConfig;

    @Override
    public void initData(@Nullable Bundle bundle) {
        formConfig = new FormConfig();
        initFormConfig(bundle);
    }

    @Override
    public void initView(@Nullable Bundle bundle, @Nullable View view) {
        radioGroup = findViewById(R.id.create_form_activity_radio);
    }

    @Override
    public int initContentView() {
        showTopBar("创建表单").setRightText("OK").setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveForm();
            }
        });
        return R.layout.activity_create_form2;
    }

    /**
     * 表单配置默认为新建表单的配置， 其他修改类的重写此方法即可类型重写此方法
     * @param bundle  表单类型 "form_type"  0：数据表单  1：流程表单
     */
    public void initFormConfig(Bundle bundle){
        List<Form> forms = SqliteExcuteCommand.get(this, Form.class);

        if (forms == null || forms.isEmpty()) {
            //加载新表单配置
            loadNewForm(bundle);
            initView();
        } else {
            //提示用户是否加载已填写的表单
            SureOrCancelDialog sureOrCancelDialog = new SureOrCancelDialog(this);
            sureOrCancelDialog.setCenterText("存在未填写完成的表单是否继续填写？");
            sureOrCancelDialog.setButtonSureText("继续").setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //加载本地表单配置
                    getSqlLiteDataToFormConfig();
                    initView();
                    sureOrCancelDialog.dismiss();
                }
            });
            sureOrCancelDialog.setButtonCancelText("不了").setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //清空本地数据表
                    FormBuilder.clearTableData(v.getContext());
                    //加载新表单配置
                    loadNewForm(bundle);
                    initView();
                    sureOrCancelDialog.dismiss();
                }
            });
            sureOrCancelDialog.show();
        }
    }

    /**
     * 初始化控件
     */
    private void initView(){
        initFragment(); //初始化fragment
        //设置选项卡跳转
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton radioButton = findViewById(checkedId);
            String tab = radioButton.getTag().toString();
            switch (tab) {
                case "form_base":
                    FragmentUtils.replace(getSupportFragmentManager(), writeBaseInformationFragment, R.id.create_form_fragment);
                    break;
                case "form_field":
                    FragmentUtils.replace(getSupportFragmentManager(), formAddFieldFragment, R.id.create_form_fragment);
                    break;
                case "form_process":
                    FragmentUtils.replace(getSupportFragmentManager(), formAddProcessFragment, R.id.create_form_fragment);
                    break;
                case "form_te_shu":
                    ToastUtils.showShort("未配置");
                    break;
                default:
                    ToastUtils.showShort("异常选项卡");
                    break;
            }
        });

        //显示出来基础设置
        RadioButton baseRadioButton = findViewById(R.id.create_form_base_option);
        baseRadioButton.setChecked(true);
    }

    /**
     * 创建新的表单
     * @param bundle  表单类型 "form_type"  0：数据表单  1：流程表单
     * @return
     */
    private FormConfig loadNewForm(Bundle bundle){
//        FormConfig config = new FormConfig();
        Form form = new Form();
        form.type = 0;
        form.id = GenerateId.getId();
        if (bundle != null) form.type = bundle.getInt("form_type",0);
        formConfig.setForm(form);

        //初始化表单字段初始值，添加2个字段
        if (FormBuilder.getInstance().getFields() != null && FormBuilder.getInstance().getFields().length >1) {
            List<FormField> formFields = getFormFieldList(FormBuilder.getInstance().getFields(), form);
            formConfig.setFormFieldList(formFields);
        } else {
            //没有字段类型直接退出该Activity
            LogUtils.e("添加默认字段失败，没有获取到字段类型！");
            ToastUtils.showLong("添加默认字段失败，没有获取到字段类型！");
            finish();
//            formConfig.setFormFieldList(new ArrayList<>());
        }

        //初始化表单初始值
        formConfig.setFormFieldOptionMap(new HashMap<>());
        formConfig.setFieldOptionReMap(new HashMap<>());
        formConfig.setFormApproveProcessList(new ArrayList<>());
        formConfig.setFormApprovePersonMap(new HashMap<>());
        formConfig.setApproveFieldPermissionMap(new HashMap<>());
        formConfig.setFormApproveProcessList(new ArrayList<>());
        formConfig.setFormFilledList(new ArrayList<>());
        formConfig.setFormUserList(new ArrayList<>());
        formConfig.setFormAdminList(new ArrayList<>());

        return formConfig;
    }

    @NonNull
    private static List<FormField> getFormFieldList(Field[] fields, Form form) {
        List<FormField> formFields = new ArrayList<>();

        Field field = fields[0];
        FormField formField = new FormField();
        formField.setId(GenerateId.getId());
        formField.setName(field.name);
        formField.setType(field.id);
        formField.setHint(field.hint);
        formField.setFormId(form.id);
        formFields.add(formField);

        Field field2 = fields[1];
        FormField formField1 = new FormField();
        formField1.setId(GenerateId.getId());
        formField1.setName(field2.name);
        formField1.setType(field2.id);
        formField1.setHint(field2.hint);
        formField1.setFormId(form.id);
        formFields.add(formField1);
        return formFields;
    }

    /**
     * 解析本地数据库表单数据
     */
    private FormConfig getSqlLiteDataToFormConfig(){

//        formConfig = new FormConfig();

        List<Form> forms = SqliteExcuteCommand.get(this, Form.class);
        formConfig.setForm(forms.get(0));

        List<FormField> formFields = SqliteExcuteCommand.get(this, FormField.class);
        if (formFields != null) formConfig.setFormFieldList(formFields);
        else formConfig.setFormFieldList(new ArrayList<>());

        List<FormFieldOption> formFieldOptions = SqliteExcuteCommand.get(this, FormFieldOption.class);
        if (formFieldOptions != null) formConfig.setFormFieldOptionList(formFieldOptions);
        else formConfig.setFormFieldList(new ArrayList<>());

        //解析本地表的选项关联的表
        List<FormOptionReField> formOptionReFields = SqliteExcuteCommand.get(this, FormOptionReField.class);
        Map<Long,List<FormField>> fieldOptionReMap = new HashMap<>();
        if (formOptionReFields != null) {
            //遍历查询到的选项和字段的关联表
            for (FormOptionReField formOptionReField : formOptionReFields) {
                //检查配置是否包含该选项
                if (fieldOptionReMap.containsKey(formOptionReField.fieldOptionId)) {
                    List<FormField> formFields1 = fieldOptionReMap.get(formOptionReField.fieldOptionId);
                    if (formFields1 == null) fieldOptionReMap.put(formOptionReField.fieldOptionId,new ArrayList<>());
                } else {
                    fieldOptionReMap.put(formOptionReField.fieldOptionId,new ArrayList<>());
                }

                for (FormField formField : formConfig.getFormFieldList()) {
                    if (formField.getId() == formOptionReField.fieldId) {
                        fieldOptionReMap.get(formOptionReField.fieldOptionId).add(formField);
                        break;
                    }
                }
            }
            formConfig.setFieldOptionReMap(fieldOptionReMap);
        } else {
            formConfig.setFieldOptionReMap(new HashMap<>());
        }

        //审批流程
        List<FormApproveProcess> formApproveProcesses = SqliteExcuteCommand.get(this, FormApproveProcess.class);
        if (formApproveProcesses != null) formConfig.setFormApproveProcessList(formApproveProcesses);
        else formConfig.setFormApproveProcessList(new ArrayList<>());

        //审批人
        List<FormApprovePerson> formApprovePeople = SqliteExcuteCommand.get(this, FormApprovePerson.class);
        Map<Long, Map<String, FormApprovePerson>> formApprovePersonMap = new HashMap<>();
        formConfig.setFormApprovePersonMap(formApprovePersonMap);
        if (formApprovePeople != null) {
            for (FormApprovePerson formApprovePerson : formApprovePeople) {
                Map<String, FormApprovePerson> stringFormApprovePersonMap = formConfig.getFormApprovePersonMap().get(formApprovePerson.processId);
                if (stringFormApprovePersonMap == null) {
                    Map<String, FormApprovePerson> mp = new HashMap<>();
                    mp.put(formApprovePerson.personId,formApprovePerson);
                    formConfig.getFormApprovePersonMap().put(formApprovePerson.processId,mp);
                } else {
                    stringFormApprovePersonMap.put(formApprovePerson.personId,formApprovePerson);
                }
            }
        } else {
            formConfig.setFormApprovePersonMap(new HashMap<>());
        }

        //审批人权限
        List<FormProcessToFieldPermission> formProcessToFieldPermissions = SqliteExcuteCommand.get(this, FormProcessToFieldPermission.class);
        formConfig.setApproveFieldPermissionMap(new HashMap<>());
        if (formProcessToFieldPermissions != null) {
            for (FormProcessToFieldPermission formProcessToFieldPermission : formProcessToFieldPermissions) {
                Map<Long, Integer> longIntegerMap = formConfig.getApproveFieldPermissionMap().get(formProcessToFieldPermission.processId);
                if (longIntegerMap == null) {
                    Map<Long, Integer> longInteger = new HashMap<>();
                    longInteger.put(formProcessToFieldPermission.fieldId,formProcessToFieldPermission.permission);
                    formConfig.getApproveFieldPermissionMap().put(formProcessToFieldPermission.processId,longInteger);
                } else {
                    longIntegerMap.put(formProcessToFieldPermission.fieldId,formProcessToFieldPermission.permission);
                }
            }
        }

        //可见部门
        List<FormFilled> formFilleds = SqliteExcuteCommand.get(this, FormFilled.class);
        if (formFilleds != null) formConfig.setFormFilledList(formFilleds);
        else formConfig.setFormFilledList(new ArrayList<>());

        //可见人员
        List<FormUser> formUsers = SqliteExcuteCommand.get(this, FormUser.class);
        if (formUsers != null) formConfig.setFormUserList(formUsers);
        else formConfig.setFormUserList(new ArrayList<>());

        //表单管理员
        List<FormAdmin> formAdminList = SqliteExcuteCommand.get(this, FormAdmin.class);
        if (formUsers != null) formConfig.setFormAdminList(formAdminList);
        else formConfig.setFormAdminList(new ArrayList<>());

        return formConfig;
    }

    /**
     * 根据formConfig初始化fragment
     */
    private void initFragment(){
        //是否显示流程设置项
        RadioButton processRadioButton = findViewById(R.id.create_form_process);
        if (formConfig.getForm().type == 1) processRadioButton.setVisibility(View.VISIBLE);
        else processRadioButton.setVisibility(View.GONE);
        //初始化fragment
        writeBaseInformationFragment = new WriteBaseInformationFragment(formConfig);
        formAddFieldFragment = new FormAddFieldFragment(formConfig);
        formAddProcessFragment = new FormAddProcessFragment(formConfig);
    }

    /**
     * 保存表单
     */
    private void saveForm(){
        handleFormData();
        saveFormToLocation();
        SelectSaveModeDialog modeDialog = new SelectSaveModeDialog(this, new SelectSaveModeDialog.ISelectSaveModeListener() {
            @Override
            public void result(int mode) {
                if (mode == FORM_SAVE_LOCATION) {
                    ToastUtils.showShort("保存完毕！");
                } else if (mode == FORM_SAVE_SERVER) {
                    saveFormToServer();
                }

            }
        });
        modeDialog.show();
    }

    /**
     * 处理表单数据
     */
    private void handleFormData(){
        //表单信息
        form = formConfig.getForm();
        LogUtils.d(JSON.toJSONString(form));

        //表单字段
        formFieldList = formConfig.getFormFieldList();
        for (int i = 0; i < formFieldList.size(); i++) formFieldList.get(i).setOrderColumn(i);//字段顺序


        int isShow = 0;
        for (FormField formField : formFieldList) {
            if (formField.isShow()) isShow ++;
            LogUtils.d("字段：" + JSON.toJSONString(formField));
        }

        if (isShow ==0 && !formFieldList.isEmpty()) {
            formFieldList.get(0).setShow(true);
        }

        //字段的选项
        formFieldOptionList = new ArrayList<>();
        for (long key: formConfig.getFormFieldOptionMap().keySet()) {
            List<FormFieldOption> formFieldOptions = formConfig.getFormFieldOptionMap().get(key);
            if (formFieldOptions != null) {
                formFieldOptionList.addAll(formFieldOptions);
            }
        }
        LogUtils.d(JSON.toJSONString(formFieldOptionList));

        //字段选项所关联的字段
        formOptionReFieldList = new ArrayList<>();
        for (long key: formConfig.getFieldOptionReMap().keySet()) {
            List<FormField> formFields = formConfig.getFieldOptionReMap().get(key);
            if (formFields != null) {
                for (FormField formField : formFields) {
                    FormOptionReField reField = new FormOptionReField(key,formField.getId());
                    formOptionReFieldList.add(reField);
                }
            }
        }
        LogUtils.d(JSON.toJSONString(formOptionReFieldList));

        //流程
        formApproveProcessList = formConfig.getFormApproveProcessList();

        //流程顺序
        for (int i = 0; i < formApproveProcessList.size(); i++) formApproveProcessList.get(i).orderColumn = i+1;
        formApprovePersonList = new ArrayList<>();
        for (Long l : formConfig.getFormApprovePersonMap().keySet()) {
            Map<String, FormApprovePerson> stringFormApprovePersonMap = formConfig.getFormApprovePersonMap().get(l);
            if (stringFormApprovePersonMap != null) formApprovePersonList.addAll(stringFormApprovePersonMap.values());
        }

        //流程审批人权限
        formProcessToFieldPermissionList = new ArrayList<>();
        for (Long l : formConfig.getApproveFieldPermissionMap().keySet()) {
            Map<Long, Integer> longIntegerMap = formConfig.getApproveFieldPermissionMap().get(l);
            if (longIntegerMap != null) {
                for (Long aLong : longIntegerMap.keySet()) {
                    Integer permission = longIntegerMap.get(aLong);
                    if (permission != null) {
                        FormProcessToFieldPermission
                                formProcessToFieldPermission =
                                new FormProcessToFieldPermission(l,aLong,permission);
                        formProcessToFieldPermissionList.add(formProcessToFieldPermission);
                    }
                }
            }
        }
    }

    List<FormProcessToFieldPermission> formProcessToFieldPermissionList;
    List<FormApprovePerson> formApprovePersonList;
    List<FormApproveProcess> formApproveProcessList;
    private List<FormFieldOption> formFieldOptionList;
    List<FormOptionReField> formOptionReFieldList;
    List<FormField> formFieldList;
    Form form;

    /**
     * 保存表单到本地
     */
    private void saveFormToLocation(){
        //保存表
        SqliteExcuteCommand.clearTable(this,Form.class);
        SqliteExcuteCommand.save(this,form);
        //保存字段
        SqliteExcuteCommand.clearTable(this,FormField.class);
        for (FormField formField : formFieldList) {
            SqliteExcuteCommand.save(this,formField);
        }
        //保存选项
        SqliteExcuteCommand.clearTable(this,FormFieldOption.class);
        for (FormFieldOption formFieldOption : formFieldOptionList) {
            SqliteExcuteCommand.save(this,formFieldOption);
        }
        //保存选项关联的字段
        SqliteExcuteCommand.clearTable(this,FormOptionReField.class);
        for (FormOptionReField reField : formOptionReFieldList) {
            LogUtils.e(JSON.toJSONString(reField));
            SqliteExcuteCommand.save(this,reField);
        }
        //保存流程
        SqliteExcuteCommand.clearTable(this,FormApproveProcess.class);
        for (FormApproveProcess formApproveProcess : formApproveProcessList) {
            SqliteExcuteCommand.save(this,formApproveProcess);
        }
        //保存审批人
        SqliteExcuteCommand.clearTable(this,FormApprovePerson.class);
        for (FormApprovePerson formApprovePerson : formApprovePersonList) {
            SqliteExcuteCommand.save(this,formApprovePerson);
        }
        //保存审批人权限
        SqliteExcuteCommand.clearTable(this,FormProcessToFieldPermission.class);
        for (FormProcessToFieldPermission formProcessToFieldPermission : formProcessToFieldPermissionList) {
            SqliteExcuteCommand.save(this,formProcessToFieldPermission);
        }
        //保存可见部门
        SqliteExcuteCommand.clearTable(this,FormFilled.class);
        for (FormFilled formFilled : formConfig.getFormFilledList()) {
            SqliteExcuteCommand.save(this,formFilled);
        }
        //保存可见人员
        SqliteExcuteCommand.clearTable(this,FormUser.class);
        for (FormUser formUser : formConfig.getFormUserList()) {
            SqliteExcuteCommand.save(this,formUser);
        }
        //保存表单管理员
        SqliteExcuteCommand.clearTable(this, FormAdmin.class);
        for (FormAdmin formAdmin : formConfig.getFormAdminList()) {
            SqliteExcuteCommand.save(this,formAdmin);
        }

        ToastUtils.showShort("保存完毕");
        printAllTest();
    }



    private void printAllTest(){
        printOne("表",SqliteExcuteCommand.get( this, FormGroup.class));
        printOne("表图标",SqliteExcuteCommand.get(this, FormIcon.class));
        printOne("表字段",SqliteExcuteCommand.get(this, FormField.class));
        printOne("表单可见部门",SqliteExcuteCommand.get(this, FormFilled.class));
        printOne("表单可见人员",SqliteExcuteCommand.get(this, FormUser.class));
        printOne("表单管理员",SqliteExcuteCommand.get(this, FormAdmin.class));
        printOne("字段选项",SqliteExcuteCommand.get(this, FormFieldOption.class));
        printOne("字段选项关联",SqliteExcuteCommand.get(this, FormOptionReField.class));
        printOne("流程",SqliteExcuteCommand.get(this, FormApproveProcess.class));
        printOne("流程审批人",SqliteExcuteCommand.get(this, FormApprovePerson.class));
        printOne("流程审批人权限",SqliteExcuteCommand.get(this, FormProcessToFieldPermission.class));
    }


    private static void printOne(String name, List<?> objects){
        if (objects == null) {
            LogUtils.e("<"+name + ">没有数据");
            return;
        }
        StringBuilder builder = new StringBuilder();
        for (Object object : objects) {
            builder.append("<").append(name).append("> ").append(JSON.toJSONString(object)).append("\n");
        }
        LogUtils.d(builder);
    }

    /**
     * 保存表单到服务器
     */
    private void saveFormToServer(){

        if (checkFormData()) {
            FormSaveData formSaveData = new FormSaveData();
            LoadingDialog loadingDialog = new LoadingDialog(this);
            loadingDialog.showLoading();
            Map<String,String> saveData = new HashMap<>();

            //汇总数据
            try {
                formSaveData.form = form;
                formSaveData.formFieldList = formFieldList;
                formSaveData.formOptionReFieldList = formOptionReFieldList;
                formSaveData.formFieldOptionList = formFieldOptionList;
                formSaveData.formApproveProcessList = formApproveProcessList;
                formSaveData.formApprovePersonList = formApprovePersonList;
                formSaveData.formProcessToFieldPermissionList = formProcessToFieldPermissionList;
                formSaveData.formFilledList = formConfig.getFormFilledList();
                formSaveData.formUserList = formConfig.getFormUserList();
                formSaveData.formAdminList = formConfig.getFormAdminList();

                if (formSaveData.form != null) saveData.put("form", JSON.toJSONString(formSaveData.form));
                if (formSaveData.formFieldList != null) saveData.put("form_field", JSON.toJSONString(formSaveData.formFieldList));
                if (formSaveData.formFieldOptionList != null && !formSaveData.formFieldOptionList.isEmpty()) saveData.put("form_field_option", JSON.toJSONString(formSaveData.formFieldOptionList));
                if (formSaveData.formOptionReFieldList != null && !formSaveData.formOptionReFieldList.isEmpty()) saveData.put("form_field_option_re", JSON.toJSONString(formSaveData.formOptionReFieldList));
                if (formSaveData.formApproveProcessList != null && !formSaveData.formApproveProcessList.isEmpty()) saveData.put("form_approve_process", JSON.toJSONString(formSaveData.formApproveProcessList));
                if (formSaveData.formApprovePersonList != null && !formSaveData.formApprovePersonList.isEmpty()) saveData.put("form_approve_person", JSON.toJSONString(formSaveData.formApprovePersonList));
                if (formSaveData.formProcessToFieldPermissionList != null && !formSaveData.formProcessToFieldPermissionList.isEmpty()) saveData.put("form_approve_process_permission", JSON.toJSONString(formSaveData.formProcessToFieldPermissionList));
                if (formSaveData.formFilledList != null && !formSaveData.formFilledList.isEmpty()) saveData.put("form_filled", JSON.toJSONString(formSaveData.formFilledList));
                if (formSaveData.formUserList != null && !formSaveData.formUserList.isEmpty()) saveData.put("form_user", JSON.toJSONString(formSaveData.formUserList));
                if (formSaveData.formAdminList != null && !formSaveData.formAdminList.isEmpty()) saveData.put("form_admin", JSON.toJSONString(formSaveData.formAdminList));

            } catch (Exception e) {
                ToastUtils.showLong(e.getMessage());
                LogUtils.e("汇总表单配置数据失败：" +e.getMessage());
                loadingDialog.dismiss();
            }

            //上传服务器
            CreateFormServiceImpl.getInstance()
                    .saveCreateForm(JSON.toJSONString(saveData))
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new MyObserver<Result>() {
                        @Override
                        public void onNext(Result result) {
                            if (result.isSuccess()) {
                                //清空本地数据库缓存数据
                                FormBuilder.clearTableData(CreateFormActivity.this);
                                ToastUtils.showShort("保存完毕");
                                finish();
                            } else {
                                ToastUtils.showShort("保存失败：" + result.getMessage());
                            }
                            loadingDialog.dismiss();
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            loadingDialog.dismiss();
                            LogUtils.e(e);
                            ToastUtils.showShort("保存失败：" + e.getMessage());
                        }
                    });
        }
    }

    /**
     * 保存服务器前检查数据
     * @return 是否符合要求
     */
    private boolean checkFormData(){
        if (StringUtils.isEmpty(formConfig.getForm().name)) {
            ToastUtils.showShort("表单名称不可为空！");
            return false;
        }

        if (formConfig.getFormFieldList().isEmpty()) {
            ToastUtils.showShort("表单没有任何字段,请先添加！");
            return false;
        }


        for (FormField formField : formConfig.getFormFieldList()) {

            //单选多选判断是否有选项
            if (formField.getType() == FormField.DUO_XUAN || formField.getType() == FormField.DAN_XUAN) {
                if (!formConfig.getFormFieldOptionMap().containsKey(formField.getId())) {
                    ToastUtils.showShort("<" + formField.getName() + "> 字段未添加选项，请添加！");
                    return false;
                }
            }
        }




        int i= 1;
        //流程表单检查
        if (formConfig.getForm().type == FORM_TYPE_PROCESS) {
            for (FormApproveProcess formApproveProcess : formConfig.getFormApproveProcessList()) {
                //如果是指定审批人类型流程必须指定审批人
                if (formApproveProcess.personType == FormAddProcessFragment.APPROVAL_SELECT_MODE_ZHI_DING) {
                    Map<String, FormApprovePerson> stringFormApprovePersonMap = formConfig.getFormApprovePersonMap().get(formApproveProcess.id);
                    if (stringFormApprovePersonMap == null || stringFormApprovePersonMap.isEmpty()) {
                        ToastUtils.showShort("第" + i + "个流程为指定审批人，请添加审批人！");
                        return false;
                    }
                }
                i++;
            }
        }


        return true;
    }

    @Override
    public void addMenuProvider(@NonNull MenuProvider provider, @NonNull LifecycleOwner owner, @NonNull Lifecycle.State state) {

    }
}